package com.wenzhoujie;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.sunday.eventbus.SDEventManager;
import com.wenzhoujie.adapter.ConfirmOrderNewAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.common.CommonInterface;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.customview.SDListViewInScroll;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.fragment.ConfirmOrderParamsFragment;
import com.wenzhoujie.fragment.OrderDetailFeeFragment;
import com.wenzhoujie.fragment.OrderDetailParamsFragment.OrderDetailParamsFragmentListener;
import com.wenzhoujie.fragment.OrderDetailPaymentsFragment;
import com.wenzhoujie.fragment.OrderDetailPaymentsFragment.OrderDetailPaymentsFragmentListener;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.dialog.SDDialogConfirm;
import com.wenzhoujie.library.dialog.SDDialogCustom;
import com.wenzhoujie.library.dialog.SDDialogCustom.SDDialogCustomListener;
import com.wenzhoujie.library.title.SDTitleSimple.SDTitleSimpleListener;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.model.CartGoodsModel;
import com.wenzhoujie.model.DeliveryModel;
import com.wenzhoujie.model.FeeinfoModel;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.ShopGoodsModel;
import com.wenzhoujie.model.SubmitShopCarModel;
import com.wenzhoujie.model.act.Calc_cartActModel;
import com.wenzhoujie.model.act.Done_cartActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

/**
 * 确认订单
 * 
 * @author js02
 * 
 */
public class ConfirmOrderActivity extends BaseActivity implements
		OnClickListener {

	public static final String EXTRA_LIST_CART_GOODS_MODEL = "extra_list_cart_goods_model";
	/** 手机登录时候的手机号码 */
	public static final String EXTRA_PHONE_LOGIN_NUMBER = "extra_phone_login_number";
	/** 手机登录时候的验证码 */
	public static final String EXTRA_PHONE_LOGIN_VALIDTE_CODE = "extra_phone_login_validte_code";
	public static final int REQUEST_CODE_DELIVERY_ADDRESS = 1;

	@ViewInject(id = R.id.act_confirm_order_ptrsv_all)
	private PullToRefreshScrollView mPtrsvAll = null;

	@ViewInject(id = R.id.act_confirm_order_lv_goods_order)
	private SDListViewInScroll mLvGoodsOrder = null;

	@ViewInject(id = R.id.act_confirm_order_btn_confirm_order)
	private Button mBtnConfirmOrder = null;

	@ViewInject(id = R.id.act_confirm_order_ll_all)
	private LinearLayout mLlAll = null;

	private Calc_cartActModel mCalc_cartActModel = null;

	private ConfirmOrderNewAdapter mAdapterConfirmOrder = null;

	private List<CartGoodsModel> mListCartGoodsModel = new ArrayList<CartGoodsModel>();

	// private List<ShopGoodsModel> mListCartGoodsModel = new
	// ArrayList<ShopGoodsModel>();

	private boolean mIsCaculateCartSuccess = false;

	// ===================请求接口提交参数

	// private CartGoodsArrayList mListCartGoods =
	// App.getApplication().getListCartGoodsModel();
	private int first_calc = 1;
	private String use_user_money; // 使用会员余额支付金额
	private String mobile = null; // 用手机快捷登录的时候输入的手机号码
	private String code = null; // 用手机快捷登陆的时候收到的验证码

	// -------------------------fragments
	private OrderDetailFeeFragment mFragFees = null;
	private OrderDetailPaymentsFragment mFragPayments = null;
	private ConfirmOrderParamsFragment mFragParams = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_SIMPLE);
		setContentView(R.layout.act_confirm_order);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init() {
		initIntentData();
		initTitle();
		registeClick();
		bindListViewData();
		CommonInterface.refreshLocalUser();
		initPullToRefreshScrollView();

	}

	private void initPullToRefreshScrollView() {
		mPtrsvAll.setMode(Mode.PULL_FROM_START);
		mPtrsvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				requestCalculateCart();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
			}

		});
		mPtrsvAll.setRefreshing();
	}

	private void initTitle() {
		mTitleSimple.setmListener(new SDTitleSimpleListener() {

			@Override
			public void onRightButtonCLick_SDTitleSimple(View v) {
				clickConfirmOrder();
			}

			@Override
			public void onLeftButtonCLick_SDTitleSimple(View v) {
				finish();
			}
		});

		mTitleSimple.setTitleTop("确认订单");
		mTitleSimple.setRightText("购买");
	}

	@SuppressWarnings("unchecked")
	private void initIntentData() {
		Intent intent = getIntent();
		List<CartGoodsModel> listCartGoodsModel = (List<CartGoodsModel>) intent
				.getSerializableExtra(EXTRA_LIST_CART_GOODS_MODEL);
		if (listCartGoodsModel != null) {
			mListCartGoodsModel = listCartGoodsModel;
		}
		mobile = intent.getStringExtra(EXTRA_PHONE_LOGIN_NUMBER);
		code = intent.getStringExtra(EXTRA_PHONE_LOGIN_VALIDTE_CODE);
	}

	private void bindListViewData() {
		mAdapterConfirmOrder = new ConfirmOrderNewAdapter(mListCartGoodsModel,
				ConfirmOrderActivity.this);
		mLvGoodsOrder.setAdapter(mAdapterConfirmOrder);
	}

	/**
	 * 获得请求确认订单接口所需的参数
	 * 
	 * @return
	 */
	private Map<String, Object> getRequestConfirmOrderParams() {
		if (!AppHelper.isLogin()) {
			return null;
		}
		Map<String, Object> mapReturn = new HashMap<String, Object>();
		mapReturn.put("act", "done_cart");
		mapReturn.put("email", AppHelper.getLocalUser().getUser_name());
		mapReturn.put("pwd", AppHelper.getLocalUser().getUser_pwd());

		if (mFragParams != null) {
			DeliveryModel deliveryModel = mFragParams.getDeliveryModel();
			if (deliveryModel != null) {
				mapReturn.put("region_lv1", deliveryModel.getRegion_lv1());
				mapReturn.put("region_lv2", deliveryModel.getRegion_lv2());
				mapReturn.put("region_lv3", deliveryModel.getRegion_lv3());
				mapReturn.put("region_lv4", deliveryModel.getRegion_lv4());
				mapReturn.put("delivery_detail",
						deliveryModel.getDelivery_detail());
				mapReturn.put("phone", deliveryModel.getPhone());
				mapReturn.put("postcode", deliveryModel.getPostcode());
				mapReturn.put("consignee", deliveryModel.getConsignee());
				// mapReturn.put("delivery_time", deliveryModel.getConsignee());
				if (mFragParams.getHasDeliveryTime()
						&& !TextUtils.isEmpty(mFragParams.getDeliver_time())
						&& !TextUtils.equals(mFragParams.getDeliver_time(),
								"尽快送达")) {
					mapReturn.put("delivery_time",
							getStringToDate(mFragParams.getDeliver_time()));
				}
				if (mFragParams.getHasDeliveryTime()
						&& (TextUtils.isEmpty(mFragParams.getDeliver_time()) || TextUtils.equals(
								mFragParams.getDeliver_time(), "尽快送达"))) {
					mapReturn.put("delivery_time", "-1");
				}
			}
			mapReturn.put("delivery_id", mFragParams.getDelivery_id());
			mapReturn.put("ecv_sn", mFragParams.getEcv_sn());
			mapReturn.put("ecv_pwd", mFragParams.getEcv_pwd());
			mapReturn.put("content", mFragParams.getContent());
			mapReturn.put("send_mobile", mFragParams.getMobile());
		}
		if (mFragPayments != null) {
			mapReturn.put("payment_id", mFragPayments.getPayment_id());
		}
		mapReturn.put("use_user_money", use_user_money);
		mapReturn.put("cartdata", getCartGoodsData());

		return mapReturn;
	}

	/**
	 * 确认订单接口
	 */
	private void requestConfirmOrder() {
		Map<String, Object> mapData = getRequestConfirmOrderParams();
		if (mapData == null) {
			return;
		}
		RequestModel model = new RequestModel(mapData);
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {
				toggleCanSubmit(false);
				AppHelper.showLoadingDialog("请稍候");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Done_cartActModel actModel = JsonUtil.json2Object(
						responseInfo.result, Done_cartActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel)) {
					if (actModel.getResponse_code() == 1) {
						if (!TextUtils.isEmpty(actModel.getOrder_id())) {
							App.getApplication().getListCartGoodsModel()
									.clear();
							SDEventManager.post(EnumEventTag.DONE_CART_SUCCESS
									.ordinal());
							// TODO 跳到支付界面
							Intent intent = new Intent(getApplicationContext(),
									PayActivity.class);
							intent.putExtra(PayActivity.EXTRA_ORDER_ID,
									actModel.getOrder_id());
							startActivity(intent);
							finish();
						} else {
							SDToast.showToast("下单失败!");
						}
					} else {
						SDToast.showToast("请求出错，下单失败!");
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {

			}

			@Override
			public void onFinish() {
				toggleCanSubmit(true);
				AppHelper.hideLoadingDialog();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	/**
	 * 获得请求计算订单接口所需的参数
	 * 
	 * @return
	 */
	private Map<String, Object> getRequestCalculateCartParams() {
		Map<String, Object> mapReturn = new HashMap<String, Object>();
		mapReturn.put("act", "calc_cart");
		if (!AppHelper.isLogin()) // 没有登录
		{
			if (!AppHelper.isEmptyString(mobile)
					&& !AppHelper.isEmptyString(code)) // 用户通过快捷登录
			{
				mapReturn.put("mobile", mobile);
				mapReturn.put("code", code);
			} else {
				return null;
			}
		} else {
			mapReturn.put("email", AppHelper.getLocalUser().getUser_name());
			mapReturn.put("pwd", AppHelper.getLocalUser().getUser_pwd());
		}
		mapReturn.put("first_calc", first_calc);
		if (first_calc != 1) // 要传入地址信息
		{
			if (mFragParams != null) {
				DeliveryModel deliveryModel = mFragParams.getDeliveryModel();
				if (deliveryModel != null) {
					mapReturn.put("region_lv1", deliveryModel.getRegion_lv1());
					mapReturn.put("region_lv2", deliveryModel.getRegion_lv2());
					mapReturn.put("region_lv3", deliveryModel.getRegion_lv3());
					mapReturn.put("region_lv4", deliveryModel.getRegion_lv4());
				}
				mapReturn.put("delivery_id", mFragParams.getDelivery_id());
				mapReturn.put("ecv_sn", mFragParams.getEcv_sn());
				mapReturn.put("ecv_pwd", mFragParams.getEcv_pwd());
			}
		}

		if (mFragPayments != null) {
			mapReturn.put("payment_id", mFragPayments.getPayment_id());
		}
		mapReturn.put("cartdata", getCartGoodsData());
		return mapReturn;
	}

	private Map<String, Object> getCartGoodsData() {
		Map<String, Object> mapCartdata = new HashMap<String, Object>();
		
		if (mListCartGoodsModel != null && mListCartGoodsModel.size() > 0) {
			for (int i = 0; i < mListCartGoodsModel.size(); i++) {
				CartGoodsModel cartModel = mListCartGoodsModel.get(i);
				mapCartdata.put(String.valueOf(i), cartModel);
			}
		}
		 
		/*List<ShopGoodsModel> shopModelList = App.getApplication()
				.getShopModelList();
		if (shopModelList.size() > 0) {
			for (int i = 0; i < shopModelList.size(); i++) {
				SubmitShopCarModel submitShopCarModel = new SubmitShopCarModel();
				submitShopCarModel.setGoods_id(shopModelList.get(i)
						.getDeal_id());
				submitShopCarModel.setNum(shopModelList.get(i).getNumber());
				submitShopCarModel.setAttr_id_a(shopModelList.get(i).getAttr());
				submitShopCarModel.setAttr_value_a(shopModelList.get(i)
						.getAttr_str());
				mapCartdata.put(String.valueOf(i), submitShopCarModel);
			}
		}*/
		return mapCartdata;
	}

	/**
	 * 请求计算订单接口
	 */
	private void requestCalculateCart() {
		Map<String, Object> mapParams = getRequestCalculateCartParams();
		if (mapParams == null) {
			return;
		}
		RequestModel model = new RequestModel(mapParams);
		RequestCallBack<String> handler = new RequestCallBack<String>() {

			@Override
			public void onStart() {
				AppHelper.showLoadingDialog("请稍候");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Calc_cartActModel actModel = JsonUtil.json2Object(
						responseInfo.result, Calc_cartActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel)) {
					int status = SDTypeParseUtil.getIntFromString(
							actModel.getStatus(), 0);
					if (status == 2) // 免登录购买，但是手机或者验证码错误
					{
						finish();
						return;
					}
					if (actModel.getResponse_code() == 1) {
						if (AppHelper.getLocalUser() == null) {
							LocalUserModel newUser = new LocalUserModel();
							newUser.setUser_id(actModel.getMobile_user_id());
							newUser.setUser_name(actModel.getMobile_user_name());
							newUser.setUser_pwd(actModel.getMobile_user_pwd());
							LocalUserModel.dealLoginSuccess(newUser, false);
						}

						mCalc_cartActModel = actModel;
						initItems(mCalc_cartActModel);
						toggleCaculateCartSuccess(true);
					} else {
						toggleCaculateCartSuccess(false);
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				toggleCaculateCartSuccess(false);
			}

			@Override
			public void onFinish() {
				AppHelper.hideLoadingDialog();
				mPtrsvAll.onRefreshComplete();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	private void toggleCaculateCartSuccess(boolean success) {
		mIsCaculateCartSuccess = success;
		if (success) {
			mLlAll.setVisibility(View.VISIBLE);
		} else {
			mLlAll.setVisibility(View.GONE);
		}
	}

	private void initItems(Calc_cartActModel model) {
		if (model != null) {
			if (first_calc == 1) {
				bindParamsData(model);
				bindPaymentsData(model);
				first_calc = 0;
			}
			bindFeeInfoData(model.getFeeinfo());
			use_user_money = model.getUse_user_money();
		}
	}

	/**
	 * 绑定配置信息fragment（手机号，留言等）
	 */
	private void bindParamsData(Calc_cartActModel model) {
		if (model != null) {
			mFragParams = new ConfirmOrderParamsFragment();
			mFragParams.setCalc_cartActModel(model);
			mFragParams.setListener(new OrderDetailParamsFragmentListener() {
				@Override
				public void onCalculate() {
					requestCalculateCart();
				}
			});
			replaceFragment(mFragParams, R.id.act_confirm_order_fl_params);
		}
	}

	/**
	 * 绑定支付方式数据
	 */
	private void bindPaymentsData(Calc_cartActModel model) {
		if (model != null) {
			mFragPayments = new OrderDetailPaymentsFragment();
			if (model.getPay_money() > 0) // 显示支付方式列表
			{
				mFragPayments.setData(model.getOrder_parm(), true);
				mFragPayments
						.setListener(new OrderDetailPaymentsFragmentListener() {

							@Override
							public void onPaymentChange() {
								requestCalculateCart();
							}
						});
			} else {
				mFragPayments.setData(model.getOrder_parm(), false);
			}
			replaceFragment(mFragPayments, R.id.act_confirm_order_fl_payments);
		}
	}

	/**
	 * 绑定费用项目数据fragment
	 * 
	 * @param listFeeInfoModel
	 */
	private void bindFeeInfoData(List<FeeinfoModel> listFeeInfoModel) {
		mFragFees = new OrderDetailFeeFragment();
		mFragFees.setListFeeinfoModel(listFeeInfoModel);
		replaceFragment(mFragFees, R.id.act_confirm_order_fl_fees);
	}

	@Override
	public void onEventMainThread(SDBaseEvent event) {
		super.onEventMainThread(event);
		switch (EnumEventTag.valueOf(event.getEventTagInt())) {
		case REFRESH_USER_MONEY_SUCCESS:
			LocalUserModel user = App.getApplication().getmLocalUser();
			if (user != null) {
				// SDViewBinder.getInstance().setTextView(mTvUserMoney,
				// user.getUser_money_format(), "未找到");
			}
			break;

		default:
			break;
		}
	}

	private void registeClick() {
		mBtnConfirmOrder.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.act_confirm_order_btn_confirm_order:
			clickConfirmOrder();
			break;

		default:
			break;
		}
	}

	/**
	 * 请求确认订单接口
	 */
	public void clickConfirmOrder() {
		if (App.getApplication().getmLocalUser() != null) // 已经登录
		{
			if (validateParams()) {
				// TODO 请求确认订单接口
				if (!mFragPayments.getHasPayment()) // 说明余额够支付，此时应该弹出确认付款窗口
				{
					showConfirmOrderDialog();
				} else {
					requestConfirmOrder();
				}
			}
		}
	}

	private void showConfirmOrderDialog() {
		new SDDialogConfirm().setTextContent("确定立即付款？")
				.setmListener(new SDDialogCustomListener() {

					@Override
					public void onDismiss(DialogInterface iDialog,
							SDDialogCustom dialog) {
					}

					@Override
					public void onClickConfirm(View v, SDDialogCustom dialog) {
						requestConfirmOrder();
					}

					@Override
					public void onClickCancel(View v, SDDialogCustom dialog) {
					}
				}).show();
	}

	private boolean validateParams() {
		// 1.判断配送地址
		if (mFragParams != null && mFragParams.getHasDeliveryAddress()) // 需要有配送地址
		{
			DeliveryModel deliveryModel = mFragParams.getDeliveryModel();
			if (deliveryModel == null) {
				SDToast.showToast("请先填写配送地址");
				return false;
			} else {
				if (TextUtils.isEmpty(deliveryModel.getConsignee())) // 收件人为空
				{
					SDToast.showToast("收件人不能为空");
					return false;
				}
				if (TextUtils.isEmpty(deliveryModel.getPhone())) // 手机号码为空
				{
					SDToast.showToast("手机号码不能为空");
					return false;
				}
				if (TextUtils.isEmpty(deliveryModel.getDelivery())) // 省市为空
				{
					SDToast.showToast("配送地区中所在省市不能为空");
					return false;
				}
				if (TextUtils.isEmpty(deliveryModel.getDelivery_detail())) // 详细地址为空
				{
					SDToast.showToast("详细地址不能为空");
					return false;
				}
				// TODO 判断是否有配送地区
				if (AppRuntimeWorker.getHas_region() == 1) {
					if (TextUtils.isEmpty(deliveryModel.getRegion_lv1())
							|| TextUtils.isEmpty(deliveryModel.getRegion_lv2())
							|| TextUtils.isEmpty(deliveryModel.getRegion_lv3())
							|| TextUtils.isEmpty(deliveryModel.getRegion_lv3())) {
						SDToast.showToast("配送地址中的，所在地区不能为空");
					}
				}
			}
		}

		// 2.判断配送方式
		if (mFragParams != null && mFragParams.getHasDeliveryMode()) // 需要配送方式
		{
			if (TextUtils.isEmpty(mFragParams.getDelivery_id())) {
				SDToast.showToast("请选择配送方式");
				return false;
			}
		}

		// 2.判断手机号
		if (mFragParams != null && mFragParams.getHasMobile()) // 需要有手机号
		{
			if (TextUtils.isEmpty(mFragParams.getMobile())) {
				SDToast.showToast("手机号不能为空");
				return false;
			}
		}

		// 3.判断支付方式
		if (mFragPayments.getHasPayment()) // 需要选择支付方式
		{
			if (AppHelper.isEmptyString(mFragPayments.getPayment_id())
					|| AppHelper.isEmptyString(mFragPayments.getPayment_code())) // 没有选择支付方式
			{
				SDToast.showToast("请选择支付方式");
				return false;
			}
		}

		if (!mIsCaculateCartSuccess) {
			return false;
		}

		return true;
	}

	private void toggleCanSubmit(boolean canSubmit) {
		if (canSubmit) {
			mBtnConfirmOrder.setOnClickListener(ConfirmOrderActivity.this);
		} else {
			mBtnConfirmOrder.setOnClickListener(null);
		}
	}

	/* 将字符串转为时间戳 */
	public static long getStringToDate(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = new Date();
		try {
			date = sdf.parse(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date.getTime() / 1000;
	}

}